﻿using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;

namespace Caius.Core.Commands
{
    /// <summary>
    /// Базовая команда
    /// </summary>
    public class BaseCommand : ICommand
    {
        private CommandResult result;
       
        /// <summary>
        /// Конструктор по-умолчанию
        /// </summary>
        public BaseCommand()
        {
        }

        /// <summary>
        /// Выполнение команды с набором строк параметров
        /// </summary>
        /// <param name="cmdParams"></param>
        /// <returns></returns>
        public CommandResult Execute(string cmdParams)
        {
            StringBuilder resBuilder = new StringBuilder();

            ApplicationManager.Instance.ClientSocket.Send(Encoding.ASCII.GetBytes(cmdParams));

            Thread.Sleep(1000);

            int bytesRead = 0;
            byte[] buffer;
            do
            {
                buffer = new byte[1024];
                buffer.Initialize();
                try
                {
                    bytesRead = ApplicationManager.Instance.ClientSocket.Receive(buffer);
                    resBuilder.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
                }
                catch (SocketException socex) 
                {
                    bytesRead = 0;
                    //throw new COMException(socex.Message);
                }
            } while (bytesRead > 0);            
            
            result = new CommandResult(resBuilder.ToString());            
            return result;
        }
    }
}
